<template>
    <div class="login-container">
        <!-- 导航栏 -->
        <van-nav-bar class="page-nav-bar" title="登录" left-text="返回" left-arrow  @click-left="router.back()">
        </van-nav-bar>
        <!-- /导航栏 -->

        <!-- 登录表单 -->
        <van-form ref="loginForm" @submit="onSubmit">
            <!-- field：输入框 -->
            <!--rules 属性定义校验规则-->
            <van-field
                v-model="dataList.user.mobile"
                name="mobile"
                placeholder="请输入手机号"
                :rules="dataList.userFormRules.mobile"
                clearable
                type="number"
                maxlength="11">
                <template #left-icon>
                    <van-icon class="iconfont headline-shouji"></van-icon>
                </template>
            </van-field>
            <van-field
                v-model="dataList.user.code"
                name="code"
                placeholder="请输入验证码"
                :rules="dataList.userFormRules.code"
                type="number"
                maxlength="6">
                <template #left-icon>
                    <van-icon center class="iconfont headline-yanzhengma"></van-icon>
                </template>
                <template #button>
                    <!--time: 倒计时时间
                    format：设置倒计时文本的内容
                    finish：倒计时结束时触发-->
                    <van-count-down
                        v-if="dataList.isCountDownShow"
                        :time="1000 * 60" format="ss s"
                        @finish="dataList.isCountDownShow = false" />
                        <!--native-type: 原生button标签的type属性
                           round：是否为圆形按钮-->
                    <van-button v-else
                        class="send-sms-btn"
                        native-type="button"
                        round
                        size="small"
                        type="default"
                        @click="onSendSms">发送验证码</van-button>
                </template>
            </van-field>
            <div class="login-btn-wrap">
                <van-button class="login-btn" block type="info" native-type="submit">
                    登录
                </van-button>
            </div>
        </van-form>
        <!-- /登录表单 -->
    </div>
</template>

<script>
import { loginAPI, sendSmsAPI } from '@/api/user'
import { reactive, ref } from 'vue'
import { Toast } from 'vant'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
export default {
  name: 'LoginIndex',
  setup () {
    const router = useRouter()
    const dataList = reactive({
      user: {
        mobile: '13500006126', // 手机号 13911111111
        code: '246810' // 验证码  246810
      },
      userFormRules: {
        // 手机号rules验证
        mobile: [{
          required: true,
          message: '手机号不能为空'
        }, {
          pattern: /^1[3|5|7|8]\d{9}$/,
          message: '手机号格式错误'
        }],
        // 验证码rules验证
        code: [{
          required: true,
          message: '验证码不能为空'
        }, {
          pattern: /^\d{6}$/,
          message: '验证码格式错误'
        }]
      },
      isCountDownShow: false // 是否展示倒计时
    })
    const store = useStore()
    const onSubmit = async () => {
      // 1. 展示登陆中 loading
      Toast.loading({
        message: '登录中...',
        forbidClick: true, // 禁用背景点击
        duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
      })
      // 2. 请求登录
      try {
        const { data } = await loginAPI(dataList.user)
        // 保存toke到vuex中
        store.commit('setUser', data.data)
        Toast.success('登录成功')

        // 登录成功，跳转回原来页面
        router.back()
      } catch (err) {
        if (err.response.status === 400) {
          Toast.fail('手机号或验证码错误')
        } else {
          Toast.fail('登录失败，请稍后重试')
        }
      }
    }
    const loginForm = ref(null)
    const onSendSms = async () => {
      // 1. 校验手机号
      try {
        // validate：验证表单，支持传入一个或多个 name 来验证单个或部分表单项
        await loginForm.value.validate('mobile')
      } catch (err) {
        return console.log('验证失败', err)
      }
      // 2. 验证通过，显示倒计时
      dataList.isCountDownShow = true
      // 3. 请求发送验证码
      try {
        await sendSmsAPI(dataList.user.mobile)
        Toast('发送成功')
      } catch (err) {
        // 发送失败，关闭倒计时
        dataList.isCountDownShow = false
        if (err.response.status === 429) {
          Toast('发送太频繁了，请稍后重试')
        } else {
          Toast('发送失败，请稍后重试')
        }
      }
    }
    return {
      onSendSms,
      onSubmit,
      dataList,
      router,
      loginForm
    }
  }

}
</script>

<style scoped lang="less">
.login-container {
    .iconfont {
        font-size: 37px;
    }
    .send-sms-btn {
        width: 152px;
        height: 46px;
        line-height: 46px;
        background-color: #ededed;
        font-size: 22px;
        color: #666;
    }
    .login-btn-wrap {
        padding: 53px 33px;
        .login-btn {
            background-color: #6db4fb;
            border: none;
        }
    }
}
</style>
